<template>
  <div class="message-publish-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/notificationT" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">发送消息</h5>
    </div>
    <!-- 消息类型选择 -->
    <div class="add-noticiation-container">
      <div class="form-group">
        <label for="message-type">消息类型</label>
        <select v-model="messageType" id="message-type" class="form-control" @change="handleMessageTypeChange">
          <option :value="90">系统消息</option>
          <option :value="91">周测消息</option>
        </select>
      </div>
      <!-- 消息内容输入 -->
      <div class="form-group">
        <label for="message-content">消息内容</label>
        <textarea v-model="messageContent" id="message-content" class="form-control" rows="5" maxlength="1000" placeholder="最多输入1000字"></textarea>
        <div v-if="messageContentError" class="text-danger">{{ messageContentError }}</div>
      </div>
      <!-- 接收人选项 -->
      <div class="form-group">
        <label>接收人选项</label>
        <div class="receiver-options">
          <label style="display: inline-block; padding: 5px; cursor: pointer;">
            <input type="radio" v-model="receiverOption" value="group" @change="toggleReceiverOption"> 按群组
          </label>
          <label style="display: inline-block; padding: 5px; cursor: pointer;">
            <input type="radio" v-model="receiverOption" value="person" @change="toggleReceiverOption"> 按人员
          </label>
        </div>
        <div v-if="receiverError" class="text-danger">{{ receiverError }}</div>
      </div>
      <!-- 按群组选择 -->
      <div v-if="receiverOption === 'group'" class="group-selection">
        <button @click="showGroupList = !showGroupList" class="btn btn-primary">选择群组</button>
        <div v-if="showGroupList" class="group-list-popup">
          <ul>
            <!-- 群组全选 -->
            <li>
              <label style="display: block; padding: 10px; cursor: pointer;">
                <input type="checkbox" v-model="selectAllGroups" @change="selectAllGroupHandler"> 全选群组
              </label>
            </li>
            <li v-for="group in groupList" :key="group.id">
              <label style="display: block; padding: 10px; cursor: pointer;">
                <input type="checkbox" :value="group.id" v-model="selectedGroups" @change="toggleGroupSelection(group.id)">
                {{ group.name }}
              </label>
              <ul>
                <li v-for="member in group.members" :key="member.id">
                  <label style="display: block; padding: 5px; cursor: pointer;">
                    <input type="checkbox" :value="member.id" v-model="selectedGroupMembers[group.id]" :disabled="!selectedGroups.includes(group.id)" @change="toggleMemberSelection(member.id)">
                    {{ member.name }}({{member.realName}})
                  </label>
                </li>
              </ul>
            </li>
          </ul>
          <button @click="showGroupList = false" class="btn btn-secondary">关闭</button>
        </div>
      </div>
      <!-- 按人员选择 -->
      <div v-if="receiverOption === 'person'" class="person-selection">
        <ul>
          <!-- 人员全选 -->
          <li>
            <label style="display: block; padding: 10px; cursor: pointer;">
              <input type="checkbox" v-model="selectAllPersons" @change="selectAllPersonHandler"> 全选人员
            </label>
          </li>
          <li v-for="person in personList" :key="person.id">
            <label style="display: block; padding: 10px; cursor: pointer;">
              <input type="checkbox" :value="person.id" v-model="selectedMembers">
              {{ person.name }}({{person.realName}})
            </label>
          </li>
        </ul>
      </div>
      <div v-if="messageType === 91" class="form-group">
        <label for="subject">科目</label>
        <select v-model="selectedSubjectId" id="subject" class="form-control" @change="handleSubjectChange">
          <option :value="null">请选择科目</option>
          <option v-for="subject in subjectDict" :key="subject.id" :value="subject.id">{{ subject.name }}</option>
        </select>
        <div v-if="subjectError" class="text-danger">{{ subjectError }}</div>
      </div>
<!--      &lt;!&ndash; 试卷选择（仅周测消息） &ndash;&gt;-->
<!--      <div v-if="messageType === 91" class="form-group">-->
<!--        <label for="exam-paper">试卷</label>-->
<!--        <select v-model="selectedExamPaperId" id="exam-paper" class="form-control" @change="updateMessageContent">-->
<!--          <option v-for="paper in examPaperList" :key="paper.id" :value="paper.id">{{ paper.name }}</option>-->
<!--        </select>-->
<!--      </div>-->
      <br/><br/>
      <!-- 提交按钮 -->
      <button @click="submitMessage" class="btn btn-primary">提交</button>
    </div>
  </div>
</template>

<script>
import http from "@/router/http";
import router from "@/router";
import {subjectTypeDict} from "@/router/dict";
export default {
  data() {
    return {
      subjectDict: [],
      messageType: 90, // 默认系统消息
      messageContent: '',
      receiverOption: 'group', // 默认按群组
      showGroupList: false,
      selectedGroups: [],
      selectedMembers: [],
      // 存储每个群组下选中的成员
      selectedGroupMembers: {},
      // 模拟群组数据
      groupList: [
        // {
        //   id: 1,
        //   name: '群组1',
        //   members: [
        //     { id: 101, name: '人员1' },
        //     { id: 102, name: '人员2' }
        //   ]
        // },
        // {
        //   id: 2,
        //   name: '群组2',
        //   members: [
        //     { id: 201, name: '人员3' },
        //     { id: 202, name: '人员4' }
        //   ]
        // }
      ].map(group => ({...group, isExpanded: false})),
      // 模拟人员数据
      personList: [
      ],
      // 模拟试卷数据
      examPaperList: [
        {id: 1, name: '试卷1'},
        {id: 2, name: '试卷2'}
      ],
      selectedExamPaperId: null,
      selectAllGroups: false, // 全选群组标记
      selectAllPersons: false, // 全选人员标记
      // 新增科目选择
      selectedSubjectId: null,
      messageTypeError: '',
      messageContentError: '',
      receiverError: '',
      subjectError: ''
    };
  },
  mounted() {
    subjectTypeDict.forEach(item => {
      this.subjectDict.push({
        id: item.id,
        name: item.name
      })
    })
    this.getGroupList();
    this.getAllUserList();
    // this.getExamPaperList(); // 初始化时获取所有试卷
  },
  methods: {
    //获取群组列表
    async getGroupList() {
      const response = await http.get(`/admin/groups/findByTeacher`);
      if (response && response.data && response.data.response) {
        response.data.response.forEach(group => {
          this.groupList.push({
            id: group.groupId,
            name: group.groupName,
            members: group.members.map(member => ({
              id: member.userId,
              name: member.userName,
              realName: member.realName
            }))
          })
        });
      }
    },
    // 获取所有用户列表
    async getAllUserList() {
      try {
        const requestData = {
          role: 1,
          supervision: 1
        }
        const response = await http.post(`/admin/user/getAllUserList`, requestData);
        response.data.response.forEach(user => {
          this.personList.push(
              {id: user.userId, name: user.userName, realName: user.realName}
          )
        });
      } catch (error) {
        console.error('获取成员列表失败：', error);
      }
    },
    toggleReceiverOption() {
      this.showGroupList = false;
      if (this.receiverOption === 'group') {
        // 当选中按群组时，清空按人员时选中的选项
        this.selectAllPersons = false;
        this.selectedMembers = this.selectedMembers.filter(memberId => {
          return !this.personList.some(person => person.id === memberId);
        });
      } else if (this.receiverOption === 'person') {
        // 当选中按人员时，清空按群组时选中的选项
        this.selectAllGroups = false;
        this.selectedGroups = [];
        this.selectedGroupMembers = {};
        this.selectedMembers = this.selectedMembers.filter(memberId => {
          let isGroupMember = false;
          this.groupList.forEach(group => {
            if (group.members.some(member => member.id === memberId)) {
              isGroupMember = true;
            }
          });
          return !isGroupMember;
        });
      }
    },
    handleMessageTypeChange() {
      if (this.messageType === 90) {
        // 如果切换到系统消息，清除试卷选择
        this.selectedExamPaperId = null;
        this.selectedSubjectId = null;
        // this.updateMessageContent();
      }
    },
    updateMessageContent() {
      if (this.messageType === 91 && this.selectedExamPaperId && this.selectedSubjectId) {
        if(this.selectedSubjectId === 1){
          this.messageContent += `<a href ='/english/weekTest/practice?examPaperId=${this.selectedExamPaperId}'>`;
        }else if(this.selectedSubjectId === 2){
          this.messageContent += `<a href ='/politics/weekTest/practice?examPaperId=${this.selectedExamPaperId}'>`;
        }else if(this.selectedSubjectId === 3){
          this.messageContent += `<a href ='/math/weekTest/practice?examPaperId=${this.selectedExamPaperId}'>`;
        }
      }
    },
    async submitMessage() {
      // 校验消息类型
      if (!this.messageType) {
        this.messageTypeError = '请选择消息类型';
        return;
      } else {
        this.messageTypeError = '';
      }

      // 校验消息内容
      if (!this.messageContent.trim()) {
        this.messageContentError = '消息内容不能为空';
        return;
      } else {
        this.messageContentError = '';
      }

      // 校验接收人
      let hasReceiver = false;
      if (this.receiverOption === 'group') {
        if (this.selectedGroups.length === 0) {
          this.receiverError = '请选择至少一个群组';
          return;
        } else {
          this.receiverError = '';
          hasReceiver = true;
        }
      } else if (this.receiverOption === 'person') {
        if (this.selectedMembers.length === 0) {
          this.receiverError = '请选择至少一个人员';
          return;
        } else {
          this.receiverError = '';
          hasReceiver = true;
        }
      }
      if (!hasReceiver) {
        return;
      }

      // 校验科目（仅周测消息）
      if (this.messageType === 91 && !this.selectedSubjectId) {
        this.subjectError = '周测消息必须选择科目';
        return;
      } else {
        this.subjectError = '';
      }
      // 合并按群组和按人员选中的成员
      let allSelectedMembers = [];

      // 处理按群组选择的成员，包括未勾选群组但勾选了成员的情况
      this.groupList.forEach(group => {
        if (this.selectedGroupMembers[group.id]) {
          allSelectedMembers = allSelectedMembers.concat(this.selectedGroupMembers[group.id]);
        }
      });

      // 合并按人员选择的成员
      allSelectedMembers = allSelectedMembers.concat(this.selectedMembers);

      // 去重处理
      const finalSelectedMembers = [...new Set(allSelectedMembers)];


      const messageData = {
        informType: this.messageType,
        content: this.messageContent,
        userIds: finalSelectedMembers,
        examPaperId: this.selectedExamPaperId, // 新增试卷ID
        subjectId: this.selectedSubjectId // 科目ID
      };
      try {
        const response = await http.post('/admin/inform/insertByTeacher', messageData);
        console.log(response)
        if(response.status===200 && response.data.code === 1){
          alert('消息发送成功');
          router.push('/notificationT');
        }
      }catch (error){
        console.error('提交消息失败：', error);
      }
    },
    // 全选群组处理函数
    selectAllGroupHandler() {
      if (this.selectAllGroups) {
        this.selectedGroups = this.groupList.map(group => group.id);
        this.groupList.forEach(group => {
          this.selectedGroupMembers[group.id] = group.members.map(member => member.id);
        });
      } else {
        this.selectedGroups = [];
        this.selectedGroupMembers = {};
      }
    },
    // 处理群组选择的变化
    toggleGroupSelection(groupId) {
      const group = this.groupList.find(group => group.id === groupId);
      if (this.selectedGroups.includes(groupId)) {
        // 群组被选中，选中该群组下的所有成员
        this.selectedGroupMembers[groupId] = group.members.map(member => member.id);
      } else {
        // 群组取消选中，取消该群组下的所有成员的选中状态
        delete this.selectedGroupMembers[groupId];
      }
    },
    // 处理成员选择的变化
    toggleMemberSelection(memberId, groupId) {
      if (!this.selectedGroupMembers[groupId]) {
        this.selectedGroupMembers[groupId] = [];
      }
      const index = this.selectedGroupMembers[groupId].indexOf(memberId);
      if (index === -1) {
        // 成员被选中
        this.selectedGroupMembers[groupId].push(memberId);
        if (!this.selectedGroups.includes(groupId)) {
          this.selectedGroups.push(groupId);
        }
      } else {
        // 成员取消选中
        this.selectedGroupMembers[groupId].splice(index, 1);
        if (this.selectedGroupMembers[groupId].length === 0) {
          delete this.selectedGroupMembers[groupId];
        }
      }
    },
    // 全选人员处理函数
    selectAllPersonHandler() {
      if (this.selectAllPersons) {
        this.selectedMembers = this.personList.map(person => person.id);
      } else {
        this.selectedMembers = [];
      }
    },
    // 新增：获取试卷列表
    async getExamPaperList(subjectId = null) {
      let url = `/admin/examPaper/list`;
      if (subjectId) {
        url += `?subjectParentId=${subjectId}`;
      }
      try {
        const response = await http.post(url);
        if (response && response.data && response.data.response) {
          response.data.response.forEach(paper => {
            this.examPaperList.push({
              id:paper.paperId,
              name:paper.name
            });
          });
        }
      }catch (error){
        console.error('获取试卷列表失败：', error);
      }
    },
    // 新增：处理科目选择变化
    handleSubjectChange() {
      if (this.selectedSubjectId) {
        this.examPaperList = [];
        // 选择了科目，根据科目ID请求试卷列表
        this.getExamPaperList(this.selectedSubjectId);
      } else {
        // 未选择科目，获取所有试卷列表
        this.getExamPaperList();
      }
    }
  }
};
</script>

<style scoped>
/* 整体布局 */
body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #f0f9f9 0%, #d8e9f9 100%);
  color: #333;
  margin: 0;
  padding: 0;
}

.receiver-options {
  display: flex;
  gap: 30px; /* 增加选项之间的间距 */
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #00b8a9 0%, #28df99 100%);
  color: white;
  padding: 15px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  margin-bottom: 20px;
}

.header .bi-chevron-left {
  color: white;
  transition: color 0.3s ease;
}

.header .bi-chevron-left:hover {
  color: #d8e9f9;
}

.header h5 {
  font-size: 1.5rem;
  font-weight: 600;
}

/* 群组编辑容器 */
.add-noticiation-container {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  margin: 20px;
}

/* 表单组样式 */
.form-group {
  margin-bottom: 20px;
}

.form-group label {
  font-size: 1rem;
  color: #555;
  margin-bottom: 10px;
  display: block;
}

.form-control {
}
.text-danger {
  color: red;
  font-size: 12px;
}
</style>